﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using JRO;
using System.Diagnostics;
using System.Data.Common;

namespace AAA.Database
{
    public class DatabaseUtil
    {
        public static string CompressAccessJetComp(string strPath, string strPassword)
        {
            
            if ((new FileInfo(strPath)).Length < 1.5 * 1024 * 1024 * 1024)
                return "";

            if (strPath == null || strPassword == null) return "Path or password can't be null";
            if (strPath.Equals("")) return "Path can't be null";

            string strDestPath = strPath.Substring(0, strPath.LastIndexOf('.')) + "tmp.mdb";

            try
            {
                Process p = new Process();
                p.StartInfo.FileName = "JetComp.exe";
                p.StartInfo.Arguments = " -src " + strPath + " -dest " + strDestPath + " -u admin -p " + strPassword;
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardOutput = true;
                p.Start();

                string output = p.StandardOutput.ReadToEnd();
                p.WaitForExit();
                
                File.Copy(strDestPath, strPath, true);
                File.Delete(strDestPath);

                return null;
            }
            catch (Exception ex)
            {
                return ex.Message + "," + ex.StackTrace;
            }
        }

        /// <summary>
        /// 壓縮修復Access資料庫工具
        /// 注：考慮到Access資料庫已被打開的情況，此處方案為先COPY原Access資料庫，再壓縮COPYAccess資料庫，再覆蓋原Access資料庫，再刪除臨時Access資料庫
        /// </summary>
        /// <param name="strPath">Access資料庫路徑</param>
        /// <param name="strPassword">Access資料庫密碼</param>
        /// <returns></returns>

        public static string CompressAccess(string strPath, string strPassword)
        {

            if ((new FileInfo(strPath)).Length < 1.5 * 1024 * 1024 * 1024)
                return "";

            if (strPath == null || strPassword == null) return "Path or password can't be null";
            if (strPath.Equals("")) return "Path can't be null";

            string path2 = strPath.Substring(0, strPath.LastIndexOf('.')) + "tmp.mdb";
            string path3 = strPath.Substring(0, strPath.LastIndexOf('.')) + "copy.mdb";
            File.Copy(strPath, path3, true);

            string dbConn3, dbConn2;
            dbConn3 = "Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Database Password=" + strPassword + ";Data Source=" + path3;
            dbConn2 = "Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Database Password=" + strPassword + ";Data Source=" + path2;// +";Jet OLEDB:Engine Type=5";

            try
            {
                JRO.JetEngine dbEngin = new JRO.JetEngine();
                dbEngin.CompactDatabase(dbConn3, dbConn2);//壓縮

                File.Copy(path2, strPath, true);//將壓縮後的Access資料庫覆蓋原Access資料庫
                File.Delete(path2);//刪除壓縮後的Access資料庫
                File.Delete(path3);//刪除壓縮前的CopyAccess資料庫

                return null;
            }
            catch (Exception ex)
            {
//                RouseCMS.log.Log.Error("AccessDbTool.compactAccessDB" + " " + e.Message);
//                RouseCMS.log.Log.Error(e.StackTrace, true);
                return ex.Message + "," + ex.StackTrace;
            }            
        }


        public static long GetSeq(IDatabase database, string strFormat, string strTableName, string strSeqFieldName)
        {            
            long lSeq = -1;
            string strDateTimeFormat;
            string strSeqFormat;
            string strConfigId = "";
            DbDataReader reader = null;
            try
            {
                strDateTimeFormat = strFormat.Substring(0, strFormat.IndexOf('x'));
                strSeqFormat = strFormat.Substring(0, strFormat.Length - 1).Replace('x', '0') + "1";

                reader = database.ExecuteQuery("SELECT MAX(" + strSeqFieldName + ") AS LastConfigId FROM " + strTableName);
                if (reader != null)
                {
                    while (reader.Read())
                    {
                        if (reader["LastConfigId"] != null)
                            strConfigId = reader["LastConfigId"].ToString();
                        else
                            strConfigId = "";
                    }
                    if (strConfigId.Trim() == "")
                    {
                        lSeq = long.Parse(DateTime.Now.ToString(strSeqFormat));
                    }
                    else if (strConfigId.Substring(0, strDateTimeFormat.Length) == DateTime.Now.ToString(strDateTimeFormat))
                    {
                        lSeq = long.Parse(strConfigId) + 1;
                    }
                    else
                    {
                        lSeq = long.Parse(DateTime.Now.ToString(strSeqFormat));
                    }

                }
                else
                {
                    lSeq = long.Parse(DateTime.Now.ToString(strSeqFormat));
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (reader != null)
                    reader.Close();
                //database.Close();
            }

            return lSeq;
        }
    }
}
